from time import sleep

from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

from base.base_page import BasePage
from page.mp_home_page import MpHomePage
from page.mp_login_page import LoginPage


class ContentMagPage(BasePage):

    def __init__(self):
        super().__init__('mp')

        self.ele_article_name = By.XPATH, '//*[@placeholder="文章名称"]'

        self.iframe_id = 'publishTinymce_ifr'

        self.iframe_content = By.CSS_SELECTOR, '#tinymce p'

        self.ele_cover = By.XPATH, '//*[contains(text(), "自动")]'

        self.ele_select = By.CSS_SELECTOR, '[placeholder="请选择"]'

        self.ele_channel = By.CSS_SELECTOR, '.el-select-dropdown__item'

        self.ele_publish = By.XPATH, '//*[text()="发表"]'

    def select_channel(self, channel):
        channel_list = self.find_ele_list(self.ele_channel)
        sleep(0.2)
        for i in channel_list:
            if i.text == channel:
                i.click()
                return
            else:
                # 没有找到时，鼠标滚动
                ActionChains(self.driver).move_to_element(i).send_keys(Keys.DOWN).perform()
                sleep(0.2)

    def publish_content(self, title, content, channel):
        # 标题
        self.input_val(self.find_ele(self.ele_article_name), title)

        # 内容
        self.driver.switch_to.frame(self.iframe_id)
        self.input_val(self.find_ele(self.iframe_content), content)
        self.driver.switch_to.default_content()

        # 封面
        self.click_element(self.find_ele(self.ele_cover))

        # 频道
        self.click_element(self.find_ele(self.ele_select))
        self.select_channel(channel)

        # 发表
        self.click_element(self.find_ele(self.ele_publish))


if __name__ == '__main__':
    LoginPage().login_page()
    sleep(1)
    MpHomePage().open_publish_article_page()
    sleep(1)
    ContentMagPage().publish_content('ddddddd', 'deeeeeeeee', 'ios')
